// @flow
import React from 'react'
import { DatePicker, Form, Input, Select, Button, message, Upload, Icon, TreeSelect } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import styles from './Home.css'
const { RangePicker } = DatePicker
import Tags from 'components/DevicePartTags'
import moment from 'moment'
const Dragger = Upload.Dragger
const SHOW_PARENT = TreeSelect.SHOW_PARENT
import { connect } from 'react-redux'

type Props = {
  userId: string,
  form: Object,
  history: Object,
  userId: string
}

const FormItem = Form.Item
const Option = Select.Option

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0
    },
    sm: {
      span: 14,
      offset: 6
    }
  }
}

type States = {
  deviceData: Array<any>,
  loading: boolean,
  customers: any,
  recordTypes: Array<any>,
  tagData: Array<string>,
  MaintenanceData: Object,
  deviceId: string,
  fileList: Array<Object>,
  faultInfoValue: string,
  faultInfos: Array<Object>,
  eventType: string
}
class MaintenanceEdit1 extends React.Component {
  props: Props
  state: States
  goBack: Function
  getCustomers: Function
  getDeviceData: Function
  getCustomerDeviceData: Function
  getRecordTypes: Function
  changeTags: Function
  changeFile1: Function
  getFiles: Function
  initChildren: Function
  getFaultInfos: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      deviceData: [],
      recordTypes: [],
      tagData: [],
      loading: false,
      MaintenanceData: {},
      customers: [{}],
      deviceId: '',
      fileList: [],
      faultInfoValue: '',
      faultInfos: [],
      eventType: ''
    }

    this.goBack = this.goBack.bind(this)
    this.changeTags = this.changeTags.bind(this)
    this.getRecordTypes = this.getRecordTypes.bind(this)
    this.getCustomers = this.getCustomers.bind(this)
    this.getDeviceData = this.getDeviceData.bind(this)
    this.getCustomerDeviceData = this.getCustomerDeviceData.bind(this)
    this.changeFile1 = this.changeFile1.bind(this)
    this.getFiles = this.getFiles.bind(this)
    this.getFaultInfos = this.getFaultInfos.bind(this)
  }
  componentWillMount () {
    this.getCustomers()
    // this.getDeviceData()
    this.getRecordTypes()
    const { data } = this.props.history.location.state
    universalFetch(`${__SERVICE_API__}device/customers/${data.customerId}/devices`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({
            code: json.code,
            message: json.message
          }))
        }
        this.props.form.resetFields(['deviceId'])
        this.setState({
          deviceData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
    this.setState({
      MaintenanceData: data,
      deviceId: data.deviceId,
      eventType: data.type,
      faultInfoValue: data.faultInfoValue || ''
    })
    this.getFiles(data)
    this.getFaultInfos()
  }
  goBack () {
    const { history } = this.props
    history.push('/business/event-log')
  }
  /**
  * 设备类型改变事件
  **/
  getFaultInfos () {
    universalFetch(`${__SERVICE_API__}device/fault/faults?isTree=true`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          faultInfos:json.result.map((data, index) => {
            let data1 = {}
            data1['key'] = '0' + '-' + index + ''
            data1['value'] = data.id + ''
            data1['label'] = data.faultName + ''
            data1['children'] = data.children
            this.initChildren(data1)
            return data1
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  initChildren (object) {
    const children = object.children.map((data, index) => {
      let data1 = {}
      data1['key'] = object.key + '-' + index + ''
      data1['value'] = data.id + ''
      data1['label'] = data.faultName + ''
      data1['children'] = data.children
      this.initChildren(data1)
      return data1
    })
    object['children'] = children
  }
  changeTags (tagData) {
    this.setState({
      tagData
    })
  }

  changeFile1 (info) {
    let fileList = info.fileList
    // 1. Limit the number of uploaded files
    //    Only to show two recent uploaded files, and old ones will be replaced by the new
    fileList = fileList.slice(-10)
    // 2. read from response and show file link
    fileList = fileList.map((file) => {
      if (file.response) {
        // Component will show file.url as link
        file.url = file.response.result.url
        file.name = file.name
      }
      return file
    })
    // 3. filter successfully uploaded files according to response from server
    fileList = fileList.filter((file) => {
      const status = info.file.status
      if (status === 'done') {
        if (file.response) {
          return file.response.code === 200000
        }
      }
      return true
    })
    console.log(fileList)
    this.setState({ fileList: fileList })
  }
  getFiles (data) {
    universalFetch(`${__SERVICE_API__}device/events1/${data.id}/files`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({
            code: json.code,
            message: json.message
          }))
        }
        this.setState({
          fileList: json.result.map((d, i) => {
            let ob = {}
            ob['uid'] = d.id
            ob['name'] = d.fileName
            ob['size'] = d.size
            ob['url'] = d.fileUrl
            ob['status'] = 'done'
            return ob
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getRecordTypes () {
    universalFetch(`${__SERVICE_API__}device/conditions?types=eventType`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          recordTypes: json.result.eventType
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  /**
   * 提交表单
   * @param  {[type]} e [description]
   * @return {[type]}   [description]
   */
  handleSubmit = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      this.setState({
        loading: true
      })
      const rangeTime = fieldsValue.rangeTime
      const values1 = {
        ...fieldsValue,
        'faultInfoValue': this.state.faultInfoValue,
        'components': this.state.tagData.join('%%'),
        'componentId': 0 // 后台设定的必须传的值，但没有实际意义
        // 'startTime': rangeTime[0].hour(0).minute(0).second(0).format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
        // 'endTime': rangeTime[1].hour(0).minute(0).second(0).format('YYYY-MM-DDTHH:mm:ss.SSSZ')
      }
      const { fileList } = this.state
      const values = {
        ...Object.assign({}, values1, { fileList })
      }
      if (values.startTime !== null) {
        values.startTime = moment.utc(rangeTime[0], 'YYYY-MM-DDTHH:mm:ss.SSSZ')
      }
      if (values.endTime !== null) {
        values.endTime = moment(rangeTime[1])
      }
      const { MaintenanceData } = this.state
      universalFetch(`${__SERVICE_API__}device/events1/${MaintenanceData.id}`, {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        method: 'PUT',
        body: JSON.stringify(values)
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        message.success('记录修改成功')
        this.props.history.push('/business/event-log')
        this.setState({
          loading: false
        })
      })
      .catch((error) => {
        console.error(error)
        this.setState({
          loading: false
        })
        message.error('记录修改失败： ' + err.message)
      })
    })
  }

  getCustomers () {
    universalFetch(`${__SERVICE_API__}device/customers?userId=${this.props.userId}&pageSize=200000`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({
            code: json.code,
            message: json.message
          }))
        }
        this.setState({
          customers: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getDeviceData () {
    universalFetch(`${__SERVICE_API__}device/devices?pageSize=20000`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({
            code: json.code,
            message: json.message
          }))
        }
        this.props.form.resetFields(['deviceId'])
        this.setState({
          deviceData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getCustomerDeviceData (val) {
    universalFetch(`${__SERVICE_API__}device/customers/${val}/devices`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({
            code: json.code,
            message: json.message
          }))
        }
        this.props.form.resetFields(['deviceId'])
        this.setState({
          deviceData: json.result,
          deviceId: ''
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  onChange = (value) => {
    this.setState({ faultInfoValue: value })
  }
  changeEventType = (value) => {
    this.setState({ eventType: value })
    if (value !== 'fault') {
      this.setState({ faultInfoValue: '' })
    }
  }
  render () {
    const { getFieldDecorator } = this.props.form
    const { loading, deviceData, customers, recordTypes, MaintenanceData, deviceId, faultInfoValue, faultInfos, eventType } = this.state
    const token = localStorage.getItem('asset_token')
    let props1 = {
      name: 'file',
      multiple: true,
      showUploadList: true,
      headers:{ 'X-Auth':token },
      action: `${__SERVICE_API__}static/statics`,
      fileList: this.state.fileList,
      onChange: this.changeFile1
    }
    // 故障
    const tProps = {
      treeData: faultInfos,
      value: faultInfoValue,
      onChange: this.onChange,
      multiple: false,
      treeCheckable: false,
      treeDefaultExpandAll: true,
      showCheckedStrategy: SHOW_PARENT,
      placeholder: '请选择故障',
      searchPlaceholder: 'Please select',
      style: {
        width: 300
      }
    }
    //  故障
    let labelFault = ''
    let frequencyFlag = eventType === 'fault'
    if (frequencyFlag) {
      labelFault = <FormItem
        {...formItemLayout}
        label='故障信息'
        hasFeedback
      >
        {getFieldDecorator('faultInfoValue', {
          rules: [{ required: false, message: '请选择故障' }],
          // initialValue: MaintenanceData.faultInfoValue
          initialValue: MaintenanceData.fault ? MaintenanceData.fault.faultName : ''
        })(
          <TreeSelect {...tProps} />
        )}
      </FormItem>
    }
    return (
      <div className={styles['main']}>
        <Form onSubmit={this.handleSubmit}>
          <FormItem {...formItemLayout} label='客户'>
            {getFieldDecorator('customerId', {
              rules: [
                { required: true, message: '请选择客户' }
              ],
              initialValue: MaintenanceData.customerId
            })(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} placeholder='请选择客户' onChange={this.getCustomerDeviceData}>
                {
                  customers.map((d, i) => {
                    return <Option key={i} value={d.id}>{d.name}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='设备'>
            {getFieldDecorator('deviceId', {
              rules: [
                { required: true, message: '请选择设备' }
              ],
              initialValue: deviceId
            })(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} placeholder='请选择设备'>
                {
                  deviceData.map((d, i) => {
                    return <Option key={i} value={d.id}>{d.name}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='设备部件'
            hasFeedback
          >
            {getFieldDecorator('components', {
              rules: [{ required: false, message: '请选择设备部件' }],
              initialValue: MaintenanceData.components ? MaintenanceData.components.split('%%') : []
            })(
              <div>
                <Input style={{ display:'none' }} placeholder='请填写部件' />
                <Tags deValue={MaintenanceData.components ? MaintenanceData.components.split('%%') : []}
                  onChange={this.changeTags} />
              </div>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='事件类型'>
            {
              getFieldDecorator('type', {
                rules: [
                  { required: true, message: '' }
                ],
                initialValue: MaintenanceData.type
              })(
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} placeholder='请选择事件类型'
                  onChange={this.changeEventType}>
                  {
                    recordTypes.map((item, i) => {
                      return <Option key={i} value={item.value}>
                        {item.label}
                      </Option>
                    })
                  }
                </Select>
              )
            }
          </FormItem>
          {labelFault}
          <FormItem {...formItemLayout} label='事件名称'>
            {getFieldDecorator('eventName', {
              rules: [
                { required: true, message: '请输入事件名称', whitespace: true }
              ],
              initialValue: MaintenanceData.eventName
            })(
              <Input placeholder='请输入事件名称' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='标签' hasFeedback>
            {getFieldDecorator('eventType', {
              rules: [
                { required: true, message: '请输入标签', whitespace: true }
              ],
              initialValue: MaintenanceData.eventType
            })(
              <Input placeholder='请输入标签' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='起止日期'>
            {getFieldDecorator('rangeTime', {
              rules: [
                { required: true, message: '请选择起止日期' }
              ],
              initialValue: [moment(MaintenanceData.startTime), moment(MaintenanceData.endTime)]
            })(
              <RangePicker style={{ width: 'auto' }}
                showTime format='YYYY-MM-DD HH:mm:ss' size='default' />
            )}
          </FormItem>
          {
            // <FormItem {...formItemLayout} label='开始时间'>
            //   {getFieldDecorator('startTime', {
            //     rules: [
            //       { required: true, message: '请选择开始时间' }
            //     ]
            //   })(
            //     <DatePicker placeholder='请选择开始时间' />
            //   )}
            // </FormItem>
            // <FormItem {...formItemLayout} label='结束时间'>
            //   {getFieldDecorator('endTime', {
            //     rules: [
            //       { required: true, message: '请选择结束时间' }
            //     ]
            //   })(
            //     <DatePicker placeholder='请选择结束时间' />
            //   )}
            // </FormItem>
          }
          <FormItem {...formItemLayout} >
            {getFieldDecorator('creator', {
              rules: [
                { required: true, message: '请输入创建人', whitespace: true }
              ],
              initialValue: MaintenanceData.creator
            })(
              <Input placeholder='请输入创建人' style={{ display: 'none' }} />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='记录负责人'>
            {getFieldDecorator('owner', {
              rules: [
                { required: true, message: '请输入负责人', whitespace: true }
              ],
              initialValue: MaintenanceData.owner
            })(
              <Input placeholder='请输入负责人' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='状态'>
            {
              getFieldDecorator('eventStatus', {
                initialValue: MaintenanceData.eventStatus
              })(
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} placeholder='请选择状态'>
                  <Option key='1' value='已解决'>已解决</Option>
                  <Option key='2' value='未解决'>未解决</Option>
                  {/* <Option key='3' value='生成工单'>生成工单</Option> */}
                </Select>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='记录描述'>
            {
              getFieldDecorator('eventDesc', {
                initialValue: MaintenanceData.eventDesc
              })(
                <Input placeholder='请填写' type='textarea' autosize={{ minRows: 6, maxRows: 30 }} />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='记录处理方法'>
            {
              getFieldDecorator('eventDeal', {
                initialValue: MaintenanceData.eventDeal
              })(
                <Input placeholder='请填写' type='textarea' autosize={{ minRows: 6, maxRows: 30 }} />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='记录实施结果'>
            {
              getFieldDecorator('eventResult', {
                initialValue: MaintenanceData.eventResult
              })(
                <Input placeholder='请填写' type='textarea' autosize={{ minRows: 6, maxRows: 30 }} />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='客户文件'>
            {
              getFieldDecorator('fileUrl', {})(
                <Dragger {...props1}>
                  <p className='ant-upload-drag-icon'>
                    <Icon type='inbox' />
                  </p>
                  <p className='ant-upload-text'>点击或者拖拽文件到该区域</p>
                  <p className='ant-upload-hint'>支持单个或批量上传，最多一次上传10个文件</p>
                </Dragger>
              )
            }
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button type='primary' htmlType='submit' size='large'
              loading={loading}
              >保存</Button>
            <Button style={{ marginLeft: '20px' }}
              onClick={this.goBack}
              >返回</Button>
          </FormItem>
        </Form>
      </div>
    )
  }
}

// const mapStateToProps = state => {
//   return {
//     userId: state.user.userId
//   }
// }
// export default connect(mapStateToProps)(MaintenanceEdit1)
const mapStatesToProps = (state) => {
  return {
    userId: state.user.userId
  }
}
export default connect(mapStatesToProps, {})(Form.create()(MaintenanceEdit1))
